<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2022/7/23
 * Time: 14:21
 */

namespace app\backstage\logic;


use app\backstage\classes\helper\JwtToken;
use app\backstage\model\ManagerRole;
use app\backstage\model\ManagerUser;
use think\Db;
use think\Exception;
use think\facade\Cookie;

class ManagerUserLogic
{
    private $pwd_suffix = 'whh951128';

    /*数据处理*/
    public function dataProcessing($params)
    {
        $data['role_id']        = $params['role_id'];
        $data['account']        = $params['account'];
        $data['password']       = md5($params['password'] . $this->pwd_suffix);
        $data['status']         = $params['status'];
        $data['parent_id']      = isset($params['parent_id']) ? $params['parent_id'] : 0;
        $data['remarks']        = isset($params['remarks']) ? $params['remarks'] : '';
        $data['sharing_ratio']  = isset($params['sharing_ratio']) ? $params['sharing_ratio'] : 0;
        $data['channel_code']   = $this->createChannelCode($params['role_id']);
        $data['scale']          = isset($params['scale']) && strlen($params['scale']) >= 1 ? $params['scale'] : 'C';

        return ['data'=>$data];
    }

    /*数据获取*/
    public function getInfo($where)
    {
        $field = 'id,role_id,account,status';
        $Account = \think\facade\App::model('Account');

        $info = $Account->getOne($where,$field);

        return $info;
    }

    /*数据添加*/
    public function addInfo($data)
    {
        $Account = \think\facade\App::model('Account');
        $res = $Account->insertRecord($data);

        if($res){
            return ['code'=>100,'msg'=>'操作成功'];
        }

        return ['code'=>102,'msg'=>'操作失败'];
    }

    public function editInfo($where,$data)
    {
        $ManagerUser = \think\facade\App::model('Account');
        $result = $ManagerUser->updateRecord($where,$data);

        if(!$result){
            return ['code'=>101,'msg'=>'操作失败'];
        }

        return ['code'=>100,'msg'=>'操作成功'];
    }

    /*更新账号信息*/
    public function editPwd($params)
    {
        $where['id'] = $params['id'];
        $data['password'] = md5($params['password'] . $this->pwd_suffix);

        $ManagerUser = \think\facade\App::model('Account');
        $result = $ManagerUser->updateRecord($where,$data);

        if(!$result){
            return ['code'=>101,'msg'=>'密码重置失败'];
        }

        return ['code'=>100,'msg'=>'密码重置成功'];
    }

    /**
     * 登录
     * @param $params
     * @return \think\response\Json
     * @Author: whh
     */
    public function sign_in($params)
    {
        $accountInfo = ManagerUser::getByAccount($params['account']);
        if (!$accountInfo) {
            return errJson('账户或密码错误');
        }
        if ($accountInfo['status'] != 1) {
            return errJson('该用户已禁用');
        }

        $isRealPwd = $this->isRealPwd($params['password'], $accountInfo['password']);

        if (!$isRealPwd) {
            return errJson('密码输入有误');
        }
        if (!$accountInfo->role->status) {
            return errJson('角色禁用');
        }
        $token = JwtToken::createToken($accountInfo->id);
        $accountInfo->last_login_time = date("Y-m-d H:i:s");
        $accountInfo->last_login_ip = request()->ip();
        $accountInfo->save();
        Cookie::set('access_token', $token, 3600 * 24 * 30);//前后端不分离项目，只能放在cookie里（本来是存到storage里客户端访问带上header头的）
        return sucJson();
    }


    /**
     * 检验账号密码正误
     * @param $pwd
     * @param $md5_pwd
     * @return bool
     * @Author: whh
     */
    public function isRealPwd($pwd, $md5_pwd)
    {
        $encrypted_str = md5($pwd . $this->pwd_suffix);
        return $encrypted_str == $md5_pwd;
    }


    /**
     * 重置密码
     * @param $manager
     * @param $oldPassword
     * @param $password
     * @return \think\response\Json
     */
    public function resetPassword($manager, $oldPassword, $password)
    {
        $isRealPwd = $this->isRealPwd($oldPassword, $manager->password);
        if (!$isRealPwd) {
            return errJson('当前密码输入有误');
        }
        $manager->password = md5($password . $this->pwd_suffix);
        $manager->save();
        return sucJson();
    }


    /**
     * App授权
     * @param ManagerUser $manager
     * @param $quick_ids Appid，逗号分隔
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function managerEmpowerApp(ManagerUser $manager, $quick_ids)
    {

        if ($manager->role->alias != 'channel' && $manager->role->alias != 'agent' && $manager->role->alias != 'eb') {
            return errJson('该角色无需授权App');
        }
        $quick_ids = array_unique(explode(',', $quick_ids));
        $quick_ids = array_unique($quick_ids);
        $haveQarr = Db::table("quick_app_mp_manager")->where("uid",$manager->id)->column('quick_id');
        $diff = array_diff($quick_ids, $haveQarr);
        if ($manager->role->alias == 'channel') {
            $msg = '投放号只能授权一个App';
            if (count($haveQarr) >= 1 && count($diff) > 0) {
                return errJson($msg);
            } elseif (count($diff) > 1) {
                return errJson($msg);
            }
        }
        foreach ($diff as $qid) {
            Db::table("quick_app_mp_manager")->insert([
                'uid' => $manager->id,
                'quick_id' => $qid,
            ]);
        }
        return sucJson();
    }


    /**
     * 设置管理员信息
     * @param $params
     * @param int $id
     * @return array
     */
    public function setUser($params, $id = 0)
    {
        $params['allow_cache'] = input('allow_cache', 1);
        if ($id) {
            $model = ManagerUser::get($id);
            $field = ['status', 'remarks','allow_cache'];
            /**
             * 代理是允许切换商务的
             */
            if ($model->role->alias == 'agent') {
                $field[] = 'parent_id';
                if (isset($params['eb_id'])) {
                    $params['parent_id'] = $params['eb_id'];
                    if ($params['parent_id']) {
                        $printRole = ManagerRole::getRoleByAlias('eb');
                        ManagerUser::where("role_id", $printRole['id'])->where("id", $params['parent_id'])->findOrFail();
                    }
                }
            }
        } else {
            $params['password'] = md5('123456' . $this->pwd_suffix);
            $field = ['account', 'password', 'role_id', 'status', 'remarks','sharing_ratio','allow_cache','channel_code','scale'];
            $oldUser = ManagerUser::where("account",$params['account'])->find();
            if ($oldUser){
                return errArr('账户已存在');
            }
            $role = ManagerRole::get($params['role_id']);
            if (!$role) {
                return errArr('角色不存在');
            }
            if ($role->alias == 'agent' || $role->alias == 'channel') {
                $field[] = 'parent_id';
                if ($role->alias == 'channel') {
                    $params['parent_id'] = $params['agent_id'];
                    $printRole = ManagerRole::getRoleByAlias('agent');
                    ManagerUser::where("role_id", $printRole['id'])->where("id", $params['parent_id'])->findOrFail();
                }
                if ($role->alias == 'agent') {
                    $params['parent_id'] = isset($params['eb_id']) ? $params['eb_id'] : 0;
                    if ($params['parent_id']) {
                        $printRole = ManagerRole::getRoleByAlias('eb');
                        ManagerUser::where("role_id", $printRole['id'])->where("id", $params['parent_id'])->findOrFail();
                    }
                }
            }

            $params['channel_code'] = $this->createChannelCode($params['role_id']);
            $params['scale'] = isset($params['scale']) && strlen($params['scale']) >= 1 ? $params['scale'] : 'C';

            $model = new ManagerUser();
        }
        $model->allowField($field)->save($params);
        return sucArr();
    }

    /*
     * 投放号渠道标识
     * */
    private function createChannelCode($role_id)
    {
        $str = '';
        $roleRecord = Db::table('cms_manager_role')->where('id',$role_id)->field('alias')->findOrEmpty();
        if(empty($roleRecord))
        {
            return $str;
        }
        if($roleRecord['alias'] != 'channel')
        {
            return $str;
        }

        do{
            $str = getNonceStr(6);
            $record = Db::table('cms_manager_user')->where('channel_code',$str)->field('id')->findOrEmpty();
        }while(!empty($record));

        return $str;
    }
}